<template>
  <div>
    <el-container>
      <el-header>
        <el-row :gutter="20">
          <el-col :span="5">
            <el-input v-model="searchData.keyword" placeholder="请输入标题/单位/村庄" :clearable="true" size="small" />
          </el-col>
          <el-col :span="6">
            <el-date-picker
              v-model="searchDate"
              style="width: 230px;"
              value-format="yyyy-MM-dd"
              size="small"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="getSearchDate"
            />
          </el-col>
          <el-col :span="3">
            <el-select v-model="searchData.isPush" clearable size="small" placeholder="是否已推送">
              <el-option
                v-for="item in isPushOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>
          <el-col :span="3">
            <el-select v-model="searchData.status" clearable size="small" placeholder="是否已解决">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>

          <el-col :span="4">
            <el-button icon="el-icon-search" size="small" @click="getContradictionListPage(1)">搜索</el-button>
          </el-col>
        </el-row>

      </el-header>

      <el-main>
        <el-table
          v-loading="listLoading"
          height="100%"
          :data="pageInfo.records"
          element-loading-text="Loading"
          border
          fit
          highlight-current-row
        >

          <el-table-column align="center" label="标题">
            <template slot-scope="scope">
              {{ scope.row.title }}
            </template>
          </el-table-column>

          <el-table-column label="提交单位" align="center">
            <template slot-scope="scope">
              {{ scope.row.inputInstitutionName }}
            </template>
          </el-table-column>

          <el-table-column label="村庄" align="center">
            <template slot-scope="scope">
              {{ scope.row.villageName }}
            </template>
          </el-table-column>

          <el-table-column label="提交人" width="110" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.inputUserName }}</span>
            </template>
          </el-table-column>

          <el-table-column label="提交时间" width="120" align="center">
            <template slot-scope="scope">
              <i class="el-icon-date" />
              <span>{{ scope.row.inputTime | dateFilter }}</span>
            </template>
          </el-table-column>

          <el-table-column label="是否推送" width="180" align="center">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.recordCount>0" type="success">
                {{ scope.row.recordCount | isPush }}
                （<span style="color: #304156">{{ scope.row.handleStatus | handleStatusFilter }}</span>）
              </el-tag>
              <el-tag v-if="scope.row.recordCount==0" type="info">{{ scope.row.recordCount | isPush }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column class-name="status-col" label="是否解决" width="110" align="center">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status==2" type="success">{{ scope.row.status | statusFilter }}</el-tag>
              <el-tag v-if="scope.row.status==1" type="info">{{ scope.row.status | statusFilter }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" fixed="right" width="220" align="center">
            <template slot-scope="scope">
              <el-button size="mini" @click="selectedContradiction = scope.row; showInfo = true">详情</el-button>
              <el-button size="mini" type="danger" :disabled="scope.row.status == 2 ? true: false" @click="pushContradiction(scope.row)">推送</el-button>
              <!-- <el-button size="mini" type="primary" :disabled="scope.row.status == 2 ? true: false || scope.row.recordCount==0" plain @click="solveContradiction(scope.$index, scope.row)">解决</el-button> -->
              <el-button size="mini" type="primary" :disabled="scope.row.status == 2 ? true: false" @click="solveContradiction(scope.$index, scope.row)">解决</el-button>
            </template>
          </el-table-column>

        </el-table>

      </el-main>

      <el-footer>
        <el-pagination
          background
          :current-page="pageInfo.current"
          :page-size="pageInfo.size"
          layout="total, prev, pager, next, jumper"
          :total="pageInfo.total"
          @current-change="getContradictionListPage"
        />
      </el-footer>

    </el-container>

    <el-dialog title="详情" :visible.sync="showInfo" width="75%" top="5vh">
      <info v-if="showInfo" :selected-contradiction-id="selectedContradiction.id" @closeDialog="showInfo = false" />
    </el-dialog>

    <el-dialog title="推送" :visible.sync="showPush" width="75%">
      <push v-if="showPush" :selected-contradiction-id="selectedContradiction.id" @refresh="getContradictionListPage" @closeDialog="showPush = false" />
    </el-dialog>

  </div>
</template>

<script>
import info from './components/info.vue';
import push from './components/push.vue';
import request from '@/utils/request'
import { formatDate } from '@/utils/formatDate.js';
import qs from 'qs';

export default {
  filters: {
    isPush(num) {
      if (num === 0) {
        return '未推送';
      }
      if (num > 0) {
        return '已推送';
      }
    },
    dateFilter(date) {
      return formatDate(new Date(date), 'yyyy-MM-dd');
    },
    statusFilter(status) {
      if (status === 0) {
        return '待提交';
      }
      if (status === 1) {
        return '待解决';
      }
      if (status === 2) {
        return '已解决';
      }
    },
    handleStatusFilter(status) {
      if (status === 0) {
        return '待处理';
      }
      if (status === 1) {
        return '已解决';
      }
      if (status === 2) {
        return '未解决';
      }
    }
  },
  components: { info, push },
  data() {
    var _self = this;
    return {
      lockReconnect: false, // 避免重复连接
      ws: null, // WebSocket的引用
      wsUrl: window.webSocketPath, // 这个要与后端提供的相同
      isPushOptions: [
        {
          value: 0,
          label: '未推送'
        },
        {
          value: 1,
          label: '已推送'
        }
      ],
      options: [
        {
          value: 1,
          label: '待解决'
        },
        {
          value: 2,
          label: '已解决'
        }
      ],
      pageInfo: {},
      listLoading: true,
      showInfo: false,
      showPush: false,
      searchDate: [],
      searchData: {
        currentPage: 1,
        status: 1
      },
      heartCheck: {
        timeout: 15000, // 毫秒
        timeoutObj: null,
        serverTimeoutObj: null,
        reset: function() {
          clearTimeout(this.timeoutObj);
          clearTimeout(this.serverTimeoutObj);
          return this;
        },
        start: function() {
          var self = this;
          this.timeoutObj = setTimeout(function() {
            // 这里发送一个心跳，后端收到后，返回一个心跳消息，
            // onmessage拿到返回的心跳就说明连接正常
            _self.ws.send('HeartBeat');
            console.log('HeartBeat');
            self.serverTimeoutObj = setTimeout(function() { // 如果超过一定时间还没重置，说明后端主动断开了
              _self.ws.close();// 如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
            }, self.timeout)
          }, this.timeout)
        }
      },
      selectedContradiction: null,
      timer: ''
    }
  },
  created() {
    // 监听键盘事件
    document.onkeydown = e => {
      var _key = window.event.keyCode;
      if (_key === 13) {
        this.getContradictionListPage(1);
      }
    }

    // 强制退出
    window.onunload = function() {
      this.ws.close();
    }
    this.createWebSocket(this.wsUrl);/** 启动连接**/

    this.getContradictionListPage(1);
  },
  mounted() {
    // this.timer = setInterval(this.getContradictionListPage, 1000 * 60);
  },
  beforeDestroy() {
    this.ws.close();
    this.heartCheck.reset();
    // clearInterval(this.timer);
  },
  methods: {
    getContradictionListPage(currentPage) {
      currentPage = currentPage == null ? this.searchData.currentPage : currentPage;
      this.listLoading = true
      this.searchData.currentPage = currentPage;
      request({
        url: '/api/contradiction/getContradictionListPage',
        method: 'get',
        params: this.searchData
      }).then((res) => {
        this.pageInfo = res.result;
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    // 推送
    pushContradiction(row) {
      if (row.status !== 2) {
        this.selectedContradiction = row;
        this.showPush = true;
      } else {
        this.$message({
          message: '已解决，不可再次推送',
          type: 'warning'
        })
      }
    },
    getSearchDate(date) {
      if (date != null) {
        this.searchData.startTime = new Date(date[0]);
        this.searchData.endTime = new Date(date[1]);
      } else {
        this.searchData.startTime = null;
        this.searchData.endTime = null;
      }
    },
    // 设置为解决
    solveContradiction(index, row) {
      this.$confirm('确认设置为解决吗？')
        .then(_ => {
          request({
            url: '/api/contradiction/solveContradiction',
            method: 'post',
            data: qs.stringify({ id: row.id }),
            headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' }
          }).then((res) => {
            if (res.resultCode == 200) {
              this.$message({
                message: res.resultCodeDesc,
                type: 'success'
              })
              this.getContradictionListPage(this.searchData.currentPage);
            } else {
              this.$message({
                duration: 6000,
                showClose: true,
                message: res.resultCodeDesc,
                type: 'warning'
              })
            }
          }).catch(_ => {})
        })
        .catch(_ => {});
    },
    initEventHandle() {
      var _self = this;
      // 连接成功建立后响应
      this.ws.onopen = function() {
        console.log('成功连接到' + _self.wsUrl);
        // 心跳检测重置
        _self.heartCheck.reset().start();
      }
      // 收到服务器消息后响应
      this.ws.onmessage = function(e) {
        // 如果获取到消息，心跳检测重置
        // 拿到任何消息都说明当前连接是正常的
        _self.heartCheck.reset().start();
        // Json转换成Object
        // var msg = eval('(' + e.data + ')');
        if (e.data === 'handleContradiction') {
          // 忽略心跳的信息，因为只要有消息进来，断线重连就会重置不会触发
          _self.getContradictionListPage();
        } else {
          // 处理消息的业务逻辑
        }
      }

      // 连接关闭后响应
      this.ws.onclose = function() {
        console.log('关闭连接');
        _self.reconnect(_self.wsUrl);// 重连
      }
      this.ws.onerror = function() {
        _self.reconnect(_self.wsUrl);// 重连
      };
    },
    reconnect(url) {
      var _self = this;
      if (this.lockReconnect) return;
      this.lockReconnect = true;
      // 没连接上会一直重连，设置延迟避免请求过多
      setTimeout(function() {
        _self.createWebSocket(_self.wsUrl);
        console.log('正在重连，当前时间' + new Date())
        _self.lockReconnect = false;
      }, 5000); // 这里设置重连间隔(ms)
    },
    createWebSocket(url) {
      try {
        if ('WebSocket' in window) {
          this.ws = new WebSocket('ws://' + url + '/webSocket');
        } else {
          this.ws = new SockJS('http://' + url + '/webSocket');
        }
        this.initEventHandle();
      } catch (e) {
        this.reconnect(this.wsUrl);
      }
    }
  }
}
</script>
<style scoped>
  html,body {
    height:100%;
  }
  .el-container {
    height: 100%;
    display: flex;
    flex-direction: column;
    text-align: center;
    width: 100%;
    position: absolute;
    top: 0;
    left:0;
  }
  .el-header {
    height: 40px !important;
    line-height: 40px;
    flex-grow: 0;
    flex-shrink: 0;
  }
  .el-footer {
    flex-grow: 0;
    flex-shrink: 0;
  }
  .el-main {
    height: 100%;
    flex-grow: 1;
    flex-shrink: 1;
    overflow-y: auto;
  }
</style>
